package basic_grammar

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

const (
	FilePath = "./src/file"
	FileName = "helloworld"
)

// 文件操作
// OS包下File结构体,bufio,io包看一下文档

func TestFile() {
	practise()
}

func testCreateFile() {
	os.Mkdir(FilePath, os.ModePerm)
	file, err := os.Create(FilePath + "/" + FileName)
	if err != nil {
		fmt.Println(err)
	}
	defer func() {
		if err := file.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	file.WriteString("hello world")
	file.WriteString("\n你好世界")

}

func testReadFile() {
	file, err := os.Open(FilePath + "/" + FileName)
	if err != nil {
		fmt.Println(err)
	}
	defer func() {
		if err := file.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	//创建一个 *Reader
	//const (
	//	defaultBufSize = 4096
	//)
	reader := bufio.NewReader(file)

	for {
		//ReadString读取直到第一次遇到delim字节, 返回一个包含已读取的数据和delim字节的字符串
		str, err := reader.ReadString('\n')
		fmt.Print(str)
		if err == io.EOF {
			break
		}
	}

	fmt.Println("\n结束")
}

func readSmallFile(fileName string) {
	content, err := ioutil.ReadFile(fileName)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(content))
}

// os.OpenFile()
// bufio包
func writeFileTest(fileName string) {
	file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	defer file.Close()
	if err != nil {
		fmt.Println(err)
		return
	}
	writer := bufio.NewWriter(file)
	writer.WriteString("\n你好\n再见\n呀哈哈")
	writer.Flush()

}

func practise() {
	writer, file := openFile(FilePath+"/newFile", os.O_WRONLY|os.O_CREATE)
	defer file.Close()
	for i := 0; i < 5; i++ {
		writer.WriteString("hello File\n")
	}
	writer.Flush()

	writer, file = openFile(FilePath+"/ahaha", os.O_WRONLY)
	defer file.Close()
	for i := 0; i < 10; i++ {
		writer.WriteString("hello yahaha\n")
	}
	writer.Flush()

	writer, file = openFile(FilePath+"/helloworld", os.O_WRONLY|os.O_APPEND)
	defer file.Close()
	writer.WriteString("\n hello new world")
	writer.Flush()

	readSmallFile(FilePath + "/test3")

	writer, file = openFile(FilePath+"/test3", os.O_WRONLY|os.O_APPEND)
	defer file.Close()
	for i := 0; i < 10; i++ {
		writer.WriteString("\nappend test3")
	}
	writer.Flush()

}

func openFile(fileName string, flag int) (*bufio.Writer, *os.File) {
	file, err := os.OpenFile(fileName, flag, os.ModePerm)
	//defer func() {
	//	if err:= file.Close();err!=nil{
	//		fmt.Println(err)
	//		return
	//	}
	//}()
	if err != nil {
		fmt.Println(err)
	}
	return bufio.NewWriter(file), file
}

func practise2() {
	file, err := os.OpenFile(FilePath+"/newFile2", os.O_WRONLY|os.O_CREATE, os.ModePerm)
	defer func() {
		if err := file.Close(); err != nil {
			fmt.Println(err)
			return
		}
	}()
	if err != nil {
		fmt.Println(err)
	}
	writer := bufio.NewWriter(file)

	for i := 0; i < 5; i++ {
		writer.WriteString("hello File")
	}
	writer.Flush()
}
